'use strict';

const db = uniCloud.database();
const collection = db.collection('food-categories');

exports.main = async (event, context) => {
  const { categoryData } = event.data || {};
  
  if (!categoryData) {
    return {
      code: 400,
      message: '缺少分类数据',
      data: null
    };
  }
  
  // 验证必填字段
  if (!categoryData.name || categoryData.name.trim() === '') {
    return {
      code: 400,
      message: '分类名称不能为空',
      data: null
    };
  }
  
  try {
    // 检查分类名称是否已存在
    const existingCategory = await collection.where({
      name: categoryData.name.trim()
    }).get();
    
    if (existingCategory.data.length > 0) {
      return {
        code: 400,
        message: '分类名称已存在',
        data: null
      };
    }
    
    // 准备插入数据
    const now = Date.now();
    const insertData = {
      _id: undefined, // 让数据库自动生成
      name: categoryData.name.trim(),
      description: categoryData.description || '',
      image: categoryData.image || '',
      sort: categoryData.sort || 0,
      status: categoryData.status !== undefined ? categoryData.status : 1,
      create_date: now,
      update_date: now
    };
    
    // 插入数据
    const result = await collection.add(insertData);
    
    return {
      code: 200,
      message: '添加成功',
      data: {
        _id: result.id,
        ...insertData
      }
    };
  } catch (error) {
    console.error('添加菜品分类失败:', error);
    return {
      code: 500,
      message: '添加失败',
      data: null
    };
  }
};